import VueRouter from 'vue-router';
import Vue from 'vue';
import NProgress from 'nprogress'; // progress bar
import 'nprogress/nprogress.css';
import { appStateInit, getDynamicRouter, logout } from '@/modules/common/service/base';
import { notification } from 'ant-design-vue';
import constantRouterMap from './constantRouterMap';
import config from '@/config/index';
import { getUrlParam } from '@zkey-webapp/general';
// import { imInit } from '@/modules/common/service/imService';
Vue.use(VueRouter);
// hack router push callback
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList =  config.whiteList; // 免登录白名单
const loginPagePath = config.loginPath;
// 首页
const defaultPagePath = config.homeIndex;
/**
 * 生成路由对象
 * @param {Store} store 状态管理机
 */
export function createRouter(store) {
    const router = new VueRouter({
        // mode: 'history',
        routes: constantRouterMap
    });

    router.beforeEach((to, from, next) => {
        //#region 新页面关闭原有的全局遮罩 loading 
        if (to && to.meta.isOldPage === true) {
            store.commit('EnableGlobalLoading');
        } else {
            store.commit('CloseGlobalLoading');
        }
        console.log(from.path,to.path);
        //#endregion
        NProgress.start();
        let tk = getUrlParam('_tk');
        // tk = '123123';
        if (tk) {
            store.commit('UpdateToken',tk);
        }
        // asyncRouter
        if (store.state.token) {
            // 已经登录则直接前往首页
            if (to.path === loginPagePath) {
                next({ path: defaultPagePath })
                NProgress.done();
            } else {
                // 是否需要拉取最新动态路由信息
                if (!store.state.dynamicRouter) {
                    getDynamicRouter(store).then((result) => {
                        appStateInit();
                        // imInit(router,store);
                        console.log(result);
                        store.commit('UpdateDynamicRouter', result);
                        // 动态添加可访问路由表
                        router.addRoutes(store.state.dynamicRouter);
                        console.log(store.state.dynamicRouter);
                        // 请求带有 redirect 重定向时，登录后自动重定向到该地址
                        const redirect = decodeURIComponent(from.query.redirect || to.path)
                        console.log(from.path, to.path, redirect);
                        if (to.path === redirect) {
                            // next();
                            next({ ...to, replace: true })
                        } else {
                            // 跳转到目的路由
                            next({ path: redirect });
                        }
                    }).catch((err) => {
                        if (err&&err!='break') {
                            notification.error({
                                message: '错误',
                                description: '请求信息失败，请重试！'
                            });
                            // 退出登录
                            // logout().then(() => next({ path: loginPagePath, query: { redirect: to.fullPath } }))
                            throw err;
                        } else{
                            
                            // 代码异常则抛出错误
                            throw err;
                        }
                    })
                } else {
                    next();
                }
            }
        } else {

            if (whiteList.filter(item => item == to.path).length > 0) {
                // 在免登录白名单中，直接进入
                next();
            } else {
                next({ path: loginPagePath, query: { redirect: to.fullPath } })
                NProgress.done();
            }
        }
    })

    router.afterEach(() => {
        NProgress.done();
    });
    return router;
}